import 'package:get/get.dart';
import 'package:wan_android_flutter/common/base/base_controller.dart';
import 'package:webview_flutter/webview_flutter.dart';

import 'common_web_state.dart';

class CommonWebLogic extends BaseController {
  final CommonWebState state = CommonWebState();

  late final WebViewController controller;

  @override
  Future<void> onInit() async {
    super.onInit();
    controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setNavigationDelegate(
        NavigationDelegate(
          onProgress: (int progress) {
            state.curProgress.value = progress;
          },
          onPageStarted: (String url) {
            state.showProgressBar.value = true;
            state.curProgress.value = 0;
          },
          onPageFinished: (String url) {
            state.showProgressBar.value = false;
          },
          onHttpError: (HttpResponseError error) {},
          onWebResourceError: (WebResourceError error) {},
          onNavigationRequest: (NavigationRequest request) {
            return NavigationDecision.navigate;
          },
        ),
      );

    if (Get.arguments != null && Get.arguments is CommonBrowserParam) {
      CommonBrowserParam commonBrowserParam = Get.arguments;
      state.title.value = commonBrowserParam.title;
      state.initialUrl.value = commonBrowserParam.url;
    } else if (Get.arguments != null && Get.arguments is Map) {
      state.title.value = Get.arguments["title"] ?? "";
      state.initialUrl.value = Get.arguments["url"] ?? "";
    }
  }

  @override
  void onLoadData() {
    super.onLoadData();
    controller.loadRequest(Uri.parse(state.initialUrl.value));
  }
}
